package cn.thoughtworks.school.controllers;

import cn.thoughtworks.school.annotations.Auth;
import cn.thoughtworks.school.entities.Application;
import cn.thoughtworks.school.entities.User;
import cn.thoughtworks.school.exceptions.BusinessException;
import cn.thoughtworks.school.services.ApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping(value = "/api/applications")
public class ApplicationController {

  @Autowired
  private ApplicationService applicationService;

  @PostMapping
  public ResponseEntity apply(@RequestBody Application application, @Auth User user) {
    applicationService.create(application, user);

    return new ResponseEntity(user, HttpStatus.CREATED);
  }

  @GetMapping("")
  public ResponseEntity getMySerialsApplications(@PageableDefault Pageable pageable,
                                                 @RequestParam String status,
                                                 @Auth User user) {
    return ResponseEntity.ok(applicationService.getMySerialsApplications(user.getId(),status,pageable));
  }


  @GetMapping("users")
  public ResponseEntity getApplications(@PageableDefault Pageable pageable,
                                                 @Auth User user) {
    return ResponseEntity.ok(applicationService.getApplications(user.getId(),pageable));
  }

  @PutMapping("{id}/handling")
  public ResponseEntity handApplication(@PathVariable Long id,
                                                 @RequestParam String status,
                                                 @Auth User user) throws BusinessException {
    applicationService.handling(user.getId(), status, id);
    return ResponseEntity.noContent().build();
  }

}
